package com.anpy.security.service;

import com.anpy.security.entity.Platform;
import com.anpy.security.entity.Role;
import com.anpy.security.repository.PlatformRepository;
import com.anpy.security.repository.RoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 角色服务类
 */
@Service
public class RoleService {

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private PlatformRepository platformRepository;

    /**
     * 获取平台下所有角色
     * 
     * @param platformCode 平台代码
     * @return 角色列表
     */
    public List<Role> getAllRolesByPlatform(String platformCode) {
        Platform platform = getPlatformByCode(platformCode);
        return roleRepository.findByPlatform(platform);
    }

    /**
     * 根据ID获取角色
     * 
     * @param id 角色ID
     * @param platformCode 平台代码
     * @return 角色对象
     */
    public Role getRoleById(Long id, String platformCode) {
        Platform platform = getPlatformByCode(platformCode);
        return roleRepository.findById(id)
                .filter(role -> role.getPlatform().getId().equals(platform.getId()))
                .orElseThrow(() -> new RuntimeException("Role not found with id: " + id + " in platform: " + platformCode));
    }

    /**
     * 创建角色
     * 
     * @param role 角色对象
     * @param platformCode 平台代码
     * @return 创建的角色
     */
    @Transactional
    public Role createRole(Role role, String platformCode) {
        Platform platform = getPlatformByCode(platformCode);
        
        // 检查角色名是否已存在
        if (roleRepository.existsByNameAndPlatform(role.getName(), platform)) {
            throw new RuntimeException("Role name already exists in platform: " + platformCode);
        }
        
        role.setPlatform(platform);
        return roleRepository.save(role);
    }

    /**
     * 更新角色
     * 
     * @param id 角色ID
     * @param roleDetails 角色详情
     * @param platformCode 平台代码
     * @return 更新后的角色
     */
    @Transactional
    public Role updateRole(Long id, Role roleDetails, String platformCode) {
        Platform platform = getPlatformByCode(platformCode);
        
        Role role = roleRepository.findById(id)
                .filter(r -> r.getPlatform().getId().equals(platform.getId()))
                .orElseThrow(() -> new RuntimeException("Role not found with id: " + id + " in platform: " + platformCode));
        
        // 更新角色信息
        role.setName(roleDetails.getName());
        role.setDescription(roleDetails.getDescription());
        
        // 更新权限（如果提供）
        if (roleDetails.getPermissions() != null && !roleDetails.getPermissions().isEmpty()) {
            role.setPermissions(roleDetails.getPermissions());
        }
        
        return roleRepository.save(role);
    }

    /**
     * 删除角色
     * 
     * @param id 角色ID
     * @param platformCode 平台代码
     */
    @Transactional
    public void deleteRole(Long id, String platformCode) {
        Platform platform = getPlatformByCode(platformCode);
        
        Role role = roleRepository.findById(id)
                .filter(r -> r.getPlatform().getId().equals(platform.getId()))
                .orElseThrow(() -> new RuntimeException("Role not found with id: " + id + " in platform: " + platformCode));
        
        roleRepository.delete(role);
    }

    /**
     * 根据平台代码获取平台
     * 
     * @param platformCode 平台代码
     * @return 平台对象
     */
    private Platform getPlatformByCode(String platformCode) {
        return platformRepository.findByCode(platformCode)
                .orElseThrow(() -> new RuntimeException("Platform not found: " + platformCode));
    }
}
